package core.september.cloudbadge.model.badge;

import java.util.Iterator;

import com.google.appengine.api.datastore.Email;
import com.google.appengine.api.datastore.PhoneNumber;
import com.google.appengine.api.datastore.PostalAddress;

import ezvcard.parameters.AddressTypeParameter;
import ezvcard.parameters.EmailTypeParameter;
import ezvcard.parameters.TelephoneTypeParameter;
import ezvcard.types.AddressType;
import ezvcard.types.EmailType;
import ezvcard.types.StructuredNameType;
import ezvcard.types.TelephoneType;



public class BaseField  extends AbsField {


	private PostalAddress postalAddress;
	private Email email;
	private PhoneNumber phoneNumber;
	private String label;



	public PostalAddress getPostalAddress() {
		return postalAddress;
	}
	public void setPostalAddress(PostalAddress postalAddress) {
		this.postalAddress = postalAddress;
	}
	public Email getEmail() {
		return email;
	}
	public void setEmail(Email email) {
		this.email = email;
	}
	public PhoneNumber getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(PhoneNumber phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getLabel() {
		return label;
	}
	public void setLabel(String label) {
		this.label = label;
	}

	public void commit() {

		AddressTypeParameter _ATP = null;
		TelephoneTypeParameter _TTP = null;
		EmailTypeParameter _ETP = null;

		switch (getfType()) {
		case WORK:
			_ATP = AddressTypeParameter.WORK;
			_TTP = TelephoneTypeParameter.WORK;
			_ETP = EmailTypeParameter.WORK;
			break;
		case HOME:
			_ATP = AddressTypeParameter.HOME;
			_TTP = TelephoneTypeParameter.HOME;
			_ETP = EmailTypeParameter.HOME;
			break;

		}

		Iterator<AddressType> it = getVcard().getAddresses().iterator();

		while(it.hasNext()) {
			AddressType at = it.next();
			boolean removal = false;
			for(AddressTypeParameter atp : at.getTypes()) {
				if(atp.equals(_ATP)) removal = true;
			}
			if(removal) it.remove();
		}

		AddressType at = new AddressType();
		at.addType(_ATP);
		at.setExtendedAddress(getPostalAddress().getAddress());
		getVcard().addAddress(at);

		Iterator<TelephoneType> tit = getVcard().getTelephoneNumbers().iterator();

		while(tit.hasNext()) {
			TelephoneType tt = tit.next();
			boolean removal = false;
			for(TelephoneTypeParameter ttp : tt.getTypes()) {
				if(ttp.equals(_TTP)) removal = true;
			}
			if(removal) tit.remove();
		}
		
		getVcard().addTelephoneNumber(getPhoneNumber().getNumber(), _TTP);
		
		
		Iterator<EmailType> et = getVcard().getEmails().iterator();

		while(et.hasNext()) {
			EmailType ety = et.next();
			boolean removal = false;
			for(EmailTypeParameter etp : ety.getTypes()) {
				if(etp.equals(_ETP)) removal = true;
			}
			if(removal) et.remove();
		}
		
		getVcard().addEmail(getEmail().getEmail(), _ETP);

	}

}
